package cluster

import (
	"github.com/rs/zerolog/log"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

type DeleteOption struct {
	KeepPvc bool
}

type Delete struct {
	*DeleteOption
	*Base
}

func NewDelete(opt *DeleteOption) *Delete {
	return &Delete{
		DeleteOption: opt,
	}
}

func (d *Delete) WithBase(base *Base) *Delete {
	d.Base = base
	return d
}

func (d *Delete) Run() error {
	return d.deleteCluster()
}

func (d *Delete) deleteCluster() (err error) {
	if d.Type == TypeAuto || d.Type == TypeMysql {
		err = d.deleteMysql()
	}
	if d.Type == TypeMysql {
		return
	}
	err = d.deleteMgr()
	if client.IgnoreNotFound(err) != nil {
		return err
	}
	return
}

func (d *Delete) deleteMysql() error {
	if !d.KeepPvc {
		mysqlCr, err := d.getMysqlCr()
		if err != nil {
			return err
		}
		if mysqlCr.Finalizers == nil {
			mysqlCr.Finalizers = make([]string, 0, 1)
		}
		mysqlCr.Finalizers = append(mysqlCr.Finalizers, pvcFinalizer)
		err = d.update(mysqlCr)
		if err != nil {
			return err
		}
	}
	err := d.deleteMysqlCr()
	if err != nil {
		return err
	}
	log.Info().Str("cluster", d.Name).Str("type", d.Type).Str("namespace", d.Namespace).Msg("delete cluster complete")
	return err
}

func (d *Delete) deleteMgr() error {
	err := d.deleteMgrCr()
	if d.KeepPvc {
		log.Info().Str("cluster", d.Name).Str("type", d.Type).Str("namespace", d.Namespace).Msg("delete cluster complete")
		return nil
	}
	err = d.removePvc()
	if err != nil {
		return err
	}
	log.Info().Str("cluster", d.Name).Str("type", d.Type).Str("namespace", d.Namespace).Msg("delete cluster complete")
	return nil
}
